<template>
  <div class="shop_member_list">
    <div class="shop_member_list_edit">
      <Form
        ref="formValidate"
        class="from"
        :model="searchObj"
        :rules="formRule"
        :show-message="false"
        label-position="left"
        inline
      >
        <Row type="flex" justify="space-between">
          <Row>
            <RadioGroup @on-change="handleTab" v-model="activeTab" type="button">
              <Radio style="width: 90px" label="会员(新)"></Radio>
              <Radio style="width: 90px" label="未转入会员"></Radio>
            </RadioGroup>
            <Button
              v-show="activeTab === '会员(新)'"
              type="default"
              style="margin-left: 20px"
              class="ivu-btn-reset"
              @click="handleModelShow"
            >
              <!-- <i class="iconsys icondepartment"></i> -->
              <Icon custom="iconsys icondepartment" size="16" />
              {{ modeShow ? '数据模式' : '图形模式' }}
            </Button>
          </Row>
          <Row>
            <FormItem class="form-item-rmicon" :show-message="false" prop="shopId" :label-width="72">
              <div slot="label" style="transform: translateX(12px);">门店名称：</div>
              <!-- <iSelectShop
                @on-change="handleShop"
                label-in-value
                permissionCode="moms:report:weixinanalytics"
                v-model="searchObj.shopId"
              /> -->
              <Select style="width:180px" filterable v-model="searchObj.shopId" label-in-value @on-change="handleShop">
                <Option v-for="item in shopList" :label="item.shopName" :value="item.shopId" :key="item.shopId">{{
                  item.shopName
                }}</Option>
              </Select>
            </FormItem>
            <FormItem>
              <Button style="width:80px" type="primary" @click="search" class="coinrevenue-btn">查询</Button>
            </FormItem>
            <FormItem>
              <Button style="width:80px"  @click="handleReset" class="coinrevenue-btn">重置</Button>
            </FormItem>
            <FormItem>
              <!-- moms:report:memberassetanalyticsexport -->
              <Button
                style="width:80px"
                v-if="hasPermission('moms:report:memberbalanceanalyticsexport')"
                @click="handleExport"
                class="coinrevenue-btn"
                >导出</Button
              >
            </FormItem>
            <FormItem v-show="!modeShow">
              <Button style="margin-left: 10px" @click="handleMoreSearch" class="coinrevenue-btn2 concrete-data">
                {{ shosMoreSearch ? '收起筛选' : '更多筛选' }}
                <Icon :type="shosMoreSearch ? 'ios-arrow-up' : 'ios-arrow-down'" />
              </Button>
            </FormItem>
          </Row>
        </Row>
        <div v-show="shosMoreSearch && !modeShow">
          <Row>
            <FormItem prop="phoneNum" :label-width="60">
              <div slot="label" style="transform: translateX(12px);">手机号：</div>
              <Input
                autocomplete="off"
                v-filterinput="{ reg: regExp.nan }"
                @on-blur="handleInputBlue('phoneNum')"
                :maxlength="11"
                v-model="searchObj.phoneNum"
                placeholder="请输入"
              />
            </FormItem>
            <FormItem :label-width="72">
              <div slot="label" style="transform: translateX(12px);">会员编号：</div>
              <Input v-model="searchObj.memberId" :maxlength="activeTab === '会员(新)' ? 12 : 16" autocomplete="off" placeholder="请输入" />
            </FormItem>
            <FormItem :label-width="72">
              <div slot="label" style="transform: translateX(12px);">会员等级：</div>
              <Select
                v-model="searchObj.level"
                @on-change="search"
                label-in-value
                style="width: 180px"
                class="select-shop-item"
                :max-tag-count="1"
              >
                <Option v-for="(item, index) in memberLevel" :key="index" :value="item.memberLevel">{{
                  item.memberLevelId ? 'V' + item.memberLevel : item.memberLevelName
                }}</Option>
              </Select>
            </FormItem>
          </Row>
          <Row type="flex" justify="start">
            <div>
              <FormItem prop="minConsumeTotal" :label-width="120">
                <div slot="label" style="transform: translateX(12px);">累计消费金额范围：</div>
                <Input
                  v-model="searchObj.minConsumeTotal"
                  @on-blur="handleInputBlue('minConsumeTotal')"
                  v-filterinput="{ reg: regExp.nand }"
                  :maxlength="12"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxConsumeTotal">
                <Input
                  v-model="searchObj.maxConsumeTotal"
                  @on-blur="handleInputBlue('maxConsumeTotal')"
                  v-filterinput="{ reg: regExp.nand }"
                  :maxlength="12"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
            <div>
              <FormItem prop="minConsumeTimes" :label-width="150">
                <div slot="label" style="transform: translateX(12px);">最近半年消费次数范围：</div>
                <Input
                  v-model="searchObj.minConsumeTimes"
                  @on-blur="handleInputBlue('minConsumeTimes')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxConsumeTimes">
                <Input
                  v-model="searchObj.maxConsumeTimes"
                  @on-blur="handleInputBlue('maxConsumeTimes')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
            <div>
              <FormItem prop="minPointBalance" :label-width="96">
                <div slot="label" style="transform: translateX(12px);">可用积分范围：</div>
                <Input
                  v-model="searchObj.minPointBalance"
                  @on-blur="handleInputBlue('minPointBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxPointBalance">
                <Input
                  v-model="searchObj.maxPointBalance"
                  @on-blur="handleInputBlue('maxPointBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
          </Row>

          <Row type="flex" justify="start">
            <div>
              <FormItem prop="minCoinBalance" :label-width="110">
                <div slot="label" style="transform: translateX(12px);">游戏币余额范围：</div>
                <Input
                  v-model="searchObj.minCoinBalance"
                  v-filterinput="{ reg: regExp.nan }"
                  @on-blur="handleInputBlue('minCoinBalance')"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxCoinBalance">
                <Input
                  v-model="searchObj.maxCoinBalance"
                  v-filterinput="{ reg: regExp.nan }"
                  @on-blur="handleInputBlue('maxCoinBalance')"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
            <div>
              <FormItem prop="minCouponBalance" :label-width="110">
                <div slot="label" style="transform: translateX(12px);">游戏券余额范围：</div>
                <Input
                  v-model="searchObj.minCouponBalance"
                  @on-blur="handleInputBlue('minCouponBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxCouponBalance">
                <Input
                  v-model="searchObj.maxCouponBalance"
                  @on-blur="handleInputBlue('maxCouponBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
            <div>
              <FormItem prop="minLotteryBalance" :label-width="96">
                <div slot="label" style="transform: translateX(12px);">彩票余额范围：</div>
                <Input
                  v-model="searchObj.minLotteryBalance"
                  @on-blur="handleInputBlue('minLotteryBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
              <span class="form_boder"></span>
              <FormItem prop="maxLotteryBalance">
                <Input
                  v-model="searchObj.maxLotteryBalance"
                  @on-blur="handleInputBlue('maxLotteryBalance')"
                  v-filterinput="{ reg: regExp.nan }"
                  :maxlength="9"
                  class="short_input"
                  autocomplete="off"
                  placeholder="请输入"
                />
              </FormItem>
            </div>
          </Row>
        </div>
      </Form>
    </div>
    <div v-if="searchObj.shopId" >
      <div v-show="!modeShow">
        <div v-show="activeTab === '未转入会员'" class="list-title">
          <span></span>
          <h3>原微信会员、实体卡会员未转入人数： {{ totalCount }}</h3>
        </div>

        <!-- <Table
        :loading="isloading"
        border
        stripe
        ref="rowSpanTable"
        :columns="columns"
        :data="resData"
      ></Table>-->
        <el-table
          v-loading="isloading"
          show-summary
          :summary-method="getSummaries"
          :header-cell-class-name="tableHeaderRowClassName"
          :row-class-name="tableRowClassName"
          element-loading-spinner="ivu-spin-dot"
          border
          stripe
          ref="table"
          :max-height="580"
          :data="resData"
          style="width: 100%; font-size:12px;"
        >
          <el-table-column
            :align="item.align"
            :header-align="item.align"
            :fixed="item.fixed"
            :prop="item.key"
            :label="item.title"
            :width="item.width"
            :min-width="item.minWidth"
            v-for="(item, index) in columns"
            :key="index"
          >
            <!-- <el-table-column :fixed="item.fixed"  :prop="item.key" :label="item.title" :width="item.width" v-for="(item, index) in columns" :key='index' >

          </el-table-column>-->

            <template slot="header">
              <span v-if="item.key === 'payAmount'">
                <span>{{ item.title }}</span>
                <!-- <Tooltip placement='top-end' content='从2018年1月1日起至今' > -->

                <Icon
                  @mouseenter.stop.native="handleMouseenter"
                  @mouseleave.stop.native="handleMouseleave"
                  style="color:#FF9901"
                  type="md-help-circle"
                ></Icon>
                <!-- </Tooltip> -->
              </span>
              <span v-else>{{ item.title }}</span>
            </template>

            <template slot-scope="scope">
              <span
                @click="handleGoDetail(scope.row)"
                style="color: #2d8cf0; cursor: pointer; text-decoration: underline #2d8cf0;"
                v-if="item.key === 'memberId'"
              >
                {{ scope.row[item.key] }}
              </span>
              <span v-else-if="item.key === 'memberSource'">
                {{ source[scope.row[item.key]] }}
              </span>
              <span v-else-if="item.key === 'memberLevel'">
                {{  'V' + scope.row[item.key] ? 'V' + scope.row[item.key] : scope.row[item.key] }}
              </span>
              <div v-else>
                {{ scope.row[item.key] }}
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="page-box" style="margin-top: 20px">
          <Page
            :total="total"
            ref="pages"
            :current.sync="searchObj.pageIndex"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            show-total
          />
        </div>
      </div>

      <div style="position:relative" v-show="modeShow && activeTab === '会员(新)'">
        <div class="list-title list-title-pie">
          <span></span>
          <h3>会员概况</h3>
        </div>
        <h2 style="padding-left: 400px">会员(新)人数：{{ sourceTatol }}</h2>
        <!-- <div class="member_list_content">
          <div style="width: 100%" class="member_list_chart">
            <div ref="source" class="chart-pie"></div>
            <div style="display: flex; align-items: center;">
              <div>
                <div v-for="(item, index) in sourceData" :key="index" class="member_list_legend">
                  <span class="legend_icon" :style="{ 'background-color': item.color }"></span>
                  <span class="legend_title">{{ item.name }}</span>
                  <span class="legend_total">{{ item.value }}</span>
                  <span class="legend_ratio">{{ item.rate }}%</span>
                </div>
              </div>
            </div>
            <div>
            </div>
          </div>
        </div> -->
        <div class="member_list_content">
          <div style="width: 100%" class="member_list_chart">
            <div ref="source" style="heigth: 200px" class="chart-pie"></div>
            <div
              :style="{ display: 'flex', 'align-items': index === 0 && item.length < 4 ? 'center' : 'normal' }"
              v-for="(item, index) in sourceData"
              :key="index"
            >
              <div>
                <div v-for="(ele, k) in item" :key="k" class="member_list_legend">
                  <span class="legend_icon" :style="{ 'background-color': ele.color }"></span>
                  <span class="legend_title">{{ ele.name }}</span>
                  <span class="legend_total">{{ ele.value }}</span>
                  <span class="legend_ratio">{{ ele.rate }}%</span>
                </div>
              </div>
            </div>
            <!-- <div>
            <div v-for="item in 5" :key="item" class="member_list_legend">
              <span class="legend_icon" :style="{ 'background-color': ' #2D8CF0;' }"></span>
              <span class="legend_title">老会员转入</span>
              <span class="legend_total">3,095.65</span>
              <span class="legend_ratio">43.54%</span>
            </div>
          </div> -->
          </div>
        </div>
              <Spin size="large"
            fix
            v-if="sourceloading"></Spin>
      </div>
      <div v-show="modeShow && activeTab === '会员(新)'">
        <div class="list-title list-title-pie">
          <span></span>
          <h3>等级概况</h3>
        </div>

        <div class="member_list_content">
          <div style="width: 100%" class="member_list_chart">
            <div ref="lever" style="heigth: 200px" class="chart-pie"></div>
            <div
              :style="{ display: 'flex', 'align-items': index === 0 && item.length < 5 ? 'center' : 'normal' }"
              v-for="(item, index) in levelData"
              :key="index"
            >
              <div>
                <div v-for="(ele, k) in item" :key="k" class="member_list_legend">
                  <span class="legend_icon" :style="{ 'background-color': ele.color }"></span>
                  <span class="legend_title">{{ ele.name }}</span>
                  <span class="legend_total">{{ ele.value }}</span>
                  <span class="legend_ratio">{{ ele.rate }}%</span>
                </div>
              </div>
            </div>
            <!-- <div>
            <div v-for="item in 5" :key="item" class="member_list_legend">
              <span class="legend_icon" :style="{ 'background-color': ' #2D8CF0;' }"></span>
              <span class="legend_title">老会员转入</span>
              <span class="legend_total">3,095.65</span>
              <span class="legend_ratio">43.54%</span>
            </div>
          </div> -->
          </div>
        </div>
      </div>
    </div>
<div v-if="!searchObj.shopId" style="text-align: center; margin-top: 114px;"><img width="320" height="240" :src="require('@/assets/images/error-page/error-shop.svg')"></div>
    <down-center perms="moms:report:memberbalanceanalytics" v-if="hasPermission('moms:report:memberbalanceanalyticsexport')" ref="downCenterRef"></down-center>
  </div>
</template>

<script>
import echarts from 'echarts'
import {
  getMemberLevelList,
  memberStatBySource,
  memberStatByLevel,
  getMemberList,
  getMemberListExport,
  getMemberListCount
} from '@/api/report/shop'
import { getShopList } from '@/api/system/store'
import { blobToXls } from '@/libs/blobToXls'
import { cloneObj } from '@/libs/cloneObj'
import iSelectShop from '@/components/i-select-shop'
import { Table, TableColumn } from 'element-ui'
import { Decimal } from 'decimal.js'
import { formatAmount } from '@/libs/tools'
import errorCaptured from '@/libs/errorCaptured'
import dayjs from 'dayjs'
import DownCenter from '@/view/components/down-center/index.vue'
import regExp from '@/libs/regExp'
const SOURCE = {
  1: '一体机',
  2: '水牌',
  3: '自主搜索',
  4: '老会员转入',
  5: '收银台',
  6: '集卡',
  7: '其他门店'
}
export default {
  name: 'report_shop_member',
  components: { iSelectShop, ElTable: Table, ElTableColumn: TableColumn, DownCenter },
  data () {
    const validate = (rule, value, callback) => {
      // console.log(rule)
      if (value === '') return callback()
      value = Number(value)
      if (Number.isNaN(value)) return callback(new Error(`${rule.messages}请输入数字`))
      // 如果是金额
      if (rule.field.endsWith('ConsumeTotal')) {
        if (!regExp.numD2.test(value)) {
          return callback(new Error(`${rule.messages}最多只能输入两位小数`))
        }
      }
      if (value > 999999999) {
        return callback(new Error(`${rule.messages}超出最大限制，最多只能输入999999999`))
      }
      let Maxkey = rule.field
      let minKey
      if (Maxkey.startsWith('max')) {
        Maxkey = rule.field
        minKey = Maxkey.replace('max', 'min')
      } else if (Maxkey.startsWith('min')) {
        Maxkey = Maxkey.replace('min', 'max')
        minKey = rule.field
      }
      // debugger
      if (rule.field.includes('max') || rule.field.includes('min')) {
        if (this.searchObj[minKey] === '' || this.searchObj[Maxkey] === '') return callback()
        // if (Maxkey.startsWith('max')) {
        if (this.searchObj[minKey] === '') return callback()
        if (new Decimal(this.searchObj[minKey]).greaterThan(Decimal(this.searchObj[Maxkey]))) {
          return callback(new Error(`${rule.messages}请输入正确的范围`))
        }
      }

      // }
      // callback(new Error('情书'))
      callback()
    }
    const phoneValidate = (rule, value, callback) => {
      if (value === '') return callback()
      if (this.regExp.phoneLength.test(value)) return callback()
      callback(new Error(`${rule.messages}`))
    }
    return {
      regExp: regExp,
      activeTab: '会员(新)',
      modeShow: true, // 默认数据模式
      isloading: false,
      shosMoreSearch: true,
      resData: [],
      // source: Object.freeze(SOURCE),
      sourceData: [], // 饼图会员概况
      sourceTatol: 0, // 新会员总数
      sourceloading: false, // 会员概况loading
      levelData: [], // 饼图等级概况
      levelLoading: false, // 等级概况loading
      totalCount: 0,
      searchObj: {
        shopId: '',
        limit: 10,
        pageIndex: 1,
        offset: 0,
        merchantId: this.$store.state.user.merchantId, // 商户id
        memberType: 0, // 会员类型:0-已转入的新会员，1-未转入的微信会员，2-所有会员
        memberId: '', // 会员编号
        phoneNum: '', // 会员手机号
        level: '', // 会员等级
        minConsumeTotal: '', // 累计消费金额最小值
        maxConsumeTotal: '', // 累计消费金额最大值
        minConsumeTimes: '', // 最近半年累计消费次数最小值
        maxConsumeTimes: '', // 最近半年累计消费次数最大值
        minPointBalance: '', // 可用积分余额最小值
        maxPointBalance: '', // 可用积分余额最大值
        minCoinBalance: '', // 游戏币余额最小值
        maxCoinBalance: '', // 游戏币余额最大值
        minCouponBalance: '', // 游戏券余额最小值
        maxCouponBalance: '', // 游戏券余额最大值
        minLotteryBalance: '', // 彩票余额最小值
        maxLotteryBalance: '' // 彩票余额最大值
      },
      formRule: {
        shopId: [{ required: true, message: '请选择门店后查询' }],
        phoneNum: [{ validator: phoneValidate, rigger: 'blur', messages: '请输入正常的手机号' }],
        minConsumeTotal: [{ validator: validate, rigger: 'blur', messages: '累计消费金额' }],
        maxConsumeTotal: [{ validator: validate, rigger: 'blur', messages: '累计消费金额' }],
        minConsumeTimes: [{ validator: validate, rigger: 'blur', messages: '最近半年消费次数' }],
        maxConsumeTimes: [{ validator: validate, rigger: 'blur', messages: '最近半年消费次数' }],
        minPointBalance: [{ validator: validate, rigger: 'blur', messages: '可用积分' }],
        maxPointBalance: [{ validator: validate, rigger: 'blur', messages: '可用积分' }],
        minCoinBalance: [{ validator: validate, rigger: 'blur', messages: '游戏币余额' }],
        maxCoinBalance: [{ validator: validate, rigger: 'blur', messages: '游戏币余额' }],
        minCouponBalance: [{ validator: validate, rigger: 'blur', messages: '游戏券余额' }],
        maxCouponBalance: [{ validator: validate, rigger: 'blur', messages: '游戏券余额' }],
        minLotteryBalance: [{ validator: validate, rigger: 'blur', messages: '彩票余额' }],
        maxLotteryBalance: [{ validator: validate, rigger: 'blur', messages: '彩票余额' }]
      },
      memberLevel: [
        { memberLevelName: '全部', memberLevel: -1 }
        // { memberLevelName: 'V0', memberLevel: 0 },
        // { memberLevelName: 'V1', memberLevel: 1 },
        // { memberLevelName: 'V2', memberLevel: 2 },
        // { memberLevelName: 'V3', memberLevel: 3 },
        // { memberLevelName: 'V4', memberLevel: 4 },
        // { memberLevelName: 'V5', memberLevel: 5 },
        // { memberLevelName: 'V6', memberLevel: 6 },
        // { memberLevelName: 'V7', memberLevel: 7 },
        // { memberLevelName: 'V8', memberLevel: 8 },
        // { memberLevelName: 'V9', memberLevel: 9 }
      ], // 会员等级
      // level: [
      //   { shopId: '12', name: 'v0', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v1', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v2', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v3', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v4', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v5', memberLevelRate: '10', value: 10 },
      //   { shopId: '12', name: 'v6', memberLevelRate: '10', value: 10 }
      // ],
      statRevenueVO: {},
      coinDetailListTotal: [],
      currencyDataList: [],
      paymentApproachList: [
        {
          payCode: 1,
          revenue: 2,
          percent: 3,
          color: 'blue'
        }
      ],
      total: 0,
      shopList: [],
      // 选中的店铺
      selectShop: {}, // label value
      columns0: [
        { title: '会员编号', key: 'memberId', align: 'center', width: '150' },
        { title: '手机号', key: 'mobileNumber', align: 'center' },
        { title: '会员等级', key: 'memberLevel', align: 'center' },
        {
          key: 'payAmount',
          align: 'center',
          title: '累计消费金额(元)'
        },
        { title: '最近一次消费日期', key: 'lastPayDate', align: 'center' },
        { title: '最近半年消费次数', key: 'payTimes', align: 'center' },
        { title: '游戏币余额', key: 'coinBalance', align: 'center' },
        { title: '游戏券余额', key: 'couponBalance', align: 'center' },
        { title: '彩票余额', key: 'lotteryBalance', align: 'center' },
        { title: '可用积分', key: 'pointBalance', align: 'center' },
        { title: '来源', key: 'memberSource', align: 'center' }
      ],
      columns1: [
        { title: '会员编号', key: 'memberId', align: 'center', width: '150' },
        { title: '手机号', key: 'mobileNumber', align: 'center' },
        { title: '会员等级', key: 'memberLevel', align: 'center' },
        {
          key: 'payAmount',
          align: 'center',
          title: '累计消费金额(元)'
        },
        { title: '最近一次消费日期', key: 'lastPayDate', align: 'center' },
        { title: '最近半年消费次数', key: 'payTimes', align: 'center' },
        { title: '游戏币余额', key: 'coinBalance', align: 'center' },
        { title: '游戏券余额', key: 'couponBalance', align: 'center' },
        { title: '彩票余额', key: 'lotteryBalance', align: 'center' },
        { title: '可用积分', key: 'pointBalance', align: 'center' },
        { title: '来源', key: 'memberSource', align: 'center' }
      ]
    }
  },
  computed: {
    columns () {
      if (this.activeTab === '会员(新)') return this.columns0
      return this.columns1
    },
    source () {
      if (this.activeTab === '会员(新)') return SOURCE
      return { 1: '未转入会员' }
    }
  },
  created () {
    this.getShopList()
    this.getMemberLevelList()
  },
  mounted () {
    // this.echartsInit(ele, option)
    // this.echartsInit(this.$refs.lever, this.level)
  },
  methods: {
    search () {
      this.searchObj.limit = 10
      this.searchObj.pageIndex = 1
      this.searchObj.offset = 0
      this.FormValidate(() => {
        this.getMemberList()
        this.getMemberListCount()
      })
    },
    // input验证
    handleInputBlue (key) {
      this.$refs.formValidate.validateField(key, valid => {
        if (valid) this.$Message.error(valid)
      })
    },
    // 表单验证
    FormValidate (cb) {
      let validFlang = true
      let currn = 0
      let keys = Object.keys(this.formRule)
      keys.forEach(key => {
        this.$refs.formValidate.validateField(key, valid => {
          if (!valid) currn = currn + 1
          console.log(key, currn)
          if (validFlang) {
            if (valid) validFlang = false
            if (!validFlang) this.$Message.error(valid)
          }
          if (currn === keys.length) cb()
        })
      })
      // console.log('validFlang', validFlang)
      // return validFlang
    },
    // 点击图形模式
    handleModelShow () {
      this.modeShow = !this.modeShow
      if (this.modeShow) {
        this.$refs.formValidate.validateField('shopId', valid => {
          if (valid) return this.$Message.error(`${valid}`)
          this.memberStatBySource()
          this.memberStatByLevel()
        })
      }
    },
    // 点击重置
    handleReset () {
      this.searchObj = {
        shopId: this.searchObj.shopId,
        limit: 10,
        pageIndex: 1,
        offset: 0,
        merchantId: this.$store.state.user.merchantId, // 商户id
        memberType: 0, // 会员类型:0-已转入的新会员，1-未转入的微信会员，2-所有会员
        memberId: '', // 会员编号
        phoneNum: '', // 会员手机号
        level: '', // 会员等级
        minConsumeTotal: '', // 累计消费金额最小值
        maxConsumeTotal: '', // 累计消费金额最大值
        minConsumeTimes: '', // 最近半年累计消费次数最小值
        maxConsumeTimes: '', // 最近半年累计消费次数最大值
        minPointBalance: '', // 可用积分余额最小值
        maxPointBalance: '', // 可用积分余额最大值
        minCoinBalance: '', // 游戏币余额最小值
        maxCoinBalance: '', // 游戏币余额最大值
        minCouponBalance: '', // 游戏券余额最小值
        maxCouponBalance: '', // 游戏券余额最大值
        minLotteryBalance: '', // 彩票余额最小值
        maxLotteryBalance: '' // 彩票余额最大值
      }
      if (this.activeTab === '会员(新)') {
        this.searchObj.memberType = 0
      } else {
        this.searchObj.memberType = 1
      }
      this.search()
    },
    // 改变店铺
    handleShop (val) {
      // console.log(val)
      this.selectShop = val
      this.searchObj.limit = 10
      this.searchObj.pageIndex = 1
      this.searchObj.offset = 0
      this.FormValidate(() => {
        this.getMemberList()
        this.getMemberListCount()
      })
      if (this.modeShow) {
        this.$refs.formValidate.validateField('shopId', valid => {
          if (valid) return this.$Message.error(`${valid}`)
          this.memberStatBySource()
          this.memberStatByLevel()
        })
      }
    },
    handleMouseenter (e) {
      this.$saas.poptip.show({
        reference: e.target,
        content: '从2018年1月1日起至今'
      })
    },
    handleMouseleave () {
      setTimeout(() => {
        this.$saas.poptip.hide()
      }, 200)
    },
    // table合计
    getSummaries (param) {
      const { columns, data } = param
      const keys = ['payAmount', 'coinBalance', 'couponBalance', 'lotteryBalance', 'pointBalance']
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (!keys.includes(column.property)) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))

        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return new Decimal(prev).add(curr).toNumber()
              // return prev + curr
            } else {
              return prev
            }
          }, 0)
          if (column.property === 'payAmount') {
            sums[index] = formatAmount(sums[index]) + ''
          } else {
            sums[index] = sums[index] + ''
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 添加表格class
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'table-row-color'
      }
      return ''
    },
    tableHeaderRowClassName ({ row, rowIndex }) {
      return 'gray-header'
    },
    // 去详情页
    handleGoDetail (param) {
      this.$router.push({
        name: 'report_shop_member_detail',
        params: {
          memberId: param.memberId,
          shopId: this.selectShop.value || this.searchObj.shopId,
          shopName: this.selectShop.label || '菱角湖万达店',
          t: +new Date()
        },
        query: { t: +new Date() }
      })
    },

    // 改变分页
    handlePage (val) {
      this.searchObj.offset = (val - 1) * this.searchObj.limit
      this.getMemberList()
    },

    // 改变分页大小
    handlePageSize (val) {
      this.searchObj.limit = val
      this.searchObj.offset = 0
      if (this.searchObj.pageIndex === 1) {
        this.getMemberList()
      } else {
        this.searchObj.pageIndex = 1
      }
    },
    echartsInit (ele, data, text, color) {
      let option = {
        title: {
          text: text,
          x: 'center',
          y: 'center',
          itemGap: 20,
          textStyle: {
            color: '#808695',
            fontFamily: '微软雅黑',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: (item) => {
            // console.log(item)
            return `${item.data.name} : ${item.data.rate}%`
          }
        },
        color: color || [],
        series: [
          {
            name: '收款方式',
            type: 'pie',
            radius: ['30%', '55%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: data
          }
        ]
      }
      const chart = echarts.init(ele) // 收款方式
      chart.setOption(option) // 收款方式
      // window.addEventListener('resize', this.chartResize)
      return chart
    },
    chartResize () {
      // chart.resize() // 收款方式
    },
    // 更多筛选
    handleMoreSearch () {
      if (this.modeShow) {
        this.shosMoreSearch = false
      } else {
        this.shosMoreSearch = !this.shosMoreSearch
      }
    },
    //
    handleTab (val) {
      this.searchObj.limit = 10
      this.searchObj.offset = 0
      this.searchObj.pageIndex = 1

      if (val === '未转入会员') this.modeShow = false
      if (val === '会员(新)') {
        this.searchObj.memberType = 0
      } else {
        this.searchObj.memberType = 1
      }
      this.FormValidate(() => {
        this.getMemberList()
        this.getMemberListCount()
      })
    },
    // 导出
    async handleExport () {
      this.FormValidate(() => {
        let extraMapParam = {}
        Object.keys(this.searchObj).map(key => {
          if (this.searchObj[key] !== '' && key !== 'limit' && key !== 'offset' && key !== 'pageIndex') {
            Reflect.set(extraMapParam, key, String(this.searchObj[key]))
          }
        })
        this.$refs.downCenterRef.addTask({
          merchantId: this.$store.state.user.merchantId,
          shopIds: [this.searchObj.shopId],
          taskModule: 'memberAssetBalance',
          operator: this.$store.state.user.userName,
          extraMapParam: extraMapParam
        })
      })
    },
    async getMemberLevelList () {
      // 获取会员等级
      const res = await getMemberLevelList({ merchantId: this.$store.state.user.merchantId })
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      if (res.data && res.data.data) {
        this.memberLevel.push(...res.data.data)
      }
    },
    // 会员概况
    async memberStatBySource () {
      this.sourceloading = true

      const [err, res] = await errorCaptured(memberStatBySource, {
        merchantId: this.$store.state.user.merchantId,
        shopId: this.searchObj.shopId
      })
      this.sourceloading = false
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
      let color = [
        '#2D8CF0',
        '#75CA8E',
        '#FBD337',
        '#CACE6E',
        '#DE9375',
        '#6DC7C7',
        '#8F78DF',
        '#B482CF',
        '#6A7FD1',
        '#ED7A8D'
      ]
      let sourceData = (res.data.data || []).map((item, index) => {
        let obj = {}
        obj.value = item.vnums
        obj.rate = item.memberSourceRate
        obj.name = SOURCE[item.memberSource]
        obj.color = color[index]
        return obj
      })
      if (res.data.data && res.data.data.length) {
        this.sourceTatol = (res.data.data || []).map(item => item.vnums).reduce((total, item) => {
          return total + item
        })
      } else {
        this.sourceTatol = 0
      }
      let result = []
      for (var i = 0, len = sourceData.length; i < len; i += 4) {
        result.push(sourceData.slice(i, i + 4))
      }
      this.sourceData = result
      this.echartsInit(this.$refs.source, sourceData, sourceData.length ? '会员概况' : '暂无数据', color)
      // this.sourceData =
    },
    // 等级概况
    async memberStatByLevel () {
      this.levelLoading = true
      const [err, res] = await errorCaptured(memberStatByLevel, {
        merchantId: this.$store.state.user.merchantId,
        shopId: this.searchObj.shopId
      })
      this.levelLoading = false
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
      // { shopId: '12', name: 'v0', memberLevelRate: '10', value: 10 },
      let color = [
        '#2D8CF0',
        '#75CA8E',
        '#FBD337',
        '#CACE6E',
        '#DE9375',
        '#6DC7C7',
        '#8F78DF',
        '#B482CF',
        '#6A7FD1',
        '#ED7A8D'
      ]
      let levelData = (res.data.data || []).map((item, index) => {
        let obj = {}
        obj.value = item.vnums
        obj.rate = item.memberLevelRate
        obj.name = `V${item.memberLevel}`
        obj.color = color[index]
        return obj
      })
      console.log(levelData)
      let result = []
      for (var i = 0, len = levelData.length; i < len; i += 5) {
        result.push(levelData.slice(i, i + 5))
      }
      // console.log(this.levelData)
      // console.log(result)
      // console.log(this.$refs.lever)
      this.levelData = result
      this.echartsInit(
        this.$refs.lever,
        levelData,
        levelData.length ? '等级概况' : '暂无数据',
        levelData.map(item => item.color)
      )
    },
    // 获取会员列表
    async getMemberList () {
      this.$refs.formValidate.validate(async valid => {
        if (!valid) return this.$Message.error(`${'请选择门店后查询'}`)
        const { level } = this.searchObj
        this.isloading = true
        const [err, res] = await errorCaptured(getMemberList, {
          ...this.searchObj,
          level: level === -1 ? '' : level
        })
        this.isloading = false
        if (err) return null
        if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
        this.resData = (res.data.data || []).map(item => {
          if (item.lastPayDate && dayjs().isValid(item.lastPayDate)) {
            item.lastPayDate = dayjs(item.lastPayDate).format('YYYY-MM-DD HH:mm:ss')
          }
          return item
        })
        this.total = res.data.totalCount
      })
    },
    // 会员结存导出
    async getMemberListExport () {
      const searchObj = cloneObj(this.searchObj)
      const { level } = searchObj
      const res = await getMemberListExport({
        ...searchObj,
        level: level === -1 ? '' : level
      })
      blobToXls(res.data, `${this.activeTab}`)
      // if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
    },
    async getShopList () {
      const res = await getShopList({
        permissionCode: 'moms:report:memberbalanceanalytics', // 查看普通订单
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      })
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)

      this.shopList = res.data.data || []
    },
    async getMemberListCount () {
      this.$refs.formValidate.validate(async valid => {
        if (!valid) return this.$Message.error(`${'请选择门店后查询'}`)
        if (this.activeTab !== '未转入会员') return null
        const { shopId } = this.searchObj
        const res = await getMemberListCount({ shopId })
        if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
        this.totalCount = res.data.data
      })
    }
  },
  beforeDestroy () {
    // window.removeEventListener('resize', this.chartResize)
  }
}
</script>

<style lang="less" scoped>
.shop_member_list {
  .shop_member_list_edit {
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    margin-bottom: -4px;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked {
    background: #2d8cf0;
    color: #fff;
  }
  .form_boder {
    display: inline-block;
    height: 33px;
    width: 8px;
    margin-right: 10px;
    // background:  #979797;
    position: relative;
  }
  .form_boder:after {
    content: '';
    display: block;
    height: 1px;
    width: 8px;
    background: #979797;
    position: absolute;
    top: 16px;
  }
  .short_input {
    width: 96px;
  }
  .list-title {
    display: flex;
    height: 100%;
    align-items: center;
    font-size: 20px;
    margin-bottom: 20px;
    padding-left: 20px;
    span {
      height: 20px;
      width: 8px;
      background: #2d8cf0;
      margin-right: 15px;
    }
  }
  .list-title-pie {
    font-size: 14px;
    height: 45px;
    background: #f8f8f9;
  }
  .chart-pie {
    // width: 40%;
    height: 200px;
    width: 400px;
  }
  .member_list_chart {
    display: flex;
  }
  .member_list_legend {
    display: flex;
    height: 40px;
    align-items: center;
    .legend_icon {
      width: 12px;
      height: 12px;
      background: #2d8cf0;
    }
    .legend_title {
      width: 100px;
      font-size: 12px;
      color: #464c5b;
      margin-left: 10px;
      text-align: justify;
    }
    .legend_total {
      width: 100px;
      font-size: 14px;
      color: #464c5b;
      letter-spacing: 0;
      text-align: justify;
    }
    .legend_ratio {
      width: 100px;
      font-size: 14px;
      color: #464c5b;
      letter-spacing: 0;
      text-align: justify;
    }
  }
}
</style>
<style lang="less">
.shop_member_list {
  .form-item-rmicon {
    .ivu-form-item-label:before {
      content: '';
      display: none;
    }
    &.ivu-form-item-error {
      .ivu-select-selection {
        border: 1px solid #dcdee2;
        // border-color: #57a3f3;
        // box-shadow: 0 0 0 2px rgba(45, 140, 240, 0.2);
      }
      .ivu-select-arrow {
        color: #808695;
      }
    }
  }
  .ivu-form-item-error {
    .ivu-input {
      border: 1px solid #dcdee2;
    }
    .ivu-input:focus {
      border-color: #57a3f3;
      box-shadow: 0 0 0 2px rgba(45, 140, 240, 0.2);
    }
  }
  .ivu-spin-dot {
    width: 32px;
    height: 32px;
    display: inline-block;
  }
  .gray-header {
    background-color: #f8f8f9;
    height: 40px;
    padding: 6px 0;
    font-weight: bold;
    color: #515a6e;
    font-size: 12px;
  }
  .table-row-color {
    background-color: #f8f8f9;
  }
}
</style>
